package main.java.com.lecture.junit.tdd.example;

import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * User: Yury
 */
public abstract class LoginServiceState {


    public void login(IAccount acc, String password, LoginService context) throws AccountNotFoundException, AccountAlreadyRevokedException, ChangePasswordException, InterruptedException {

        if (acc.passwordMatches(password)) {
            if (acc.isRevoked()) {
                throw new AccountAlreadyRevokedException("Account is already revoked");
            }
            if (context.enoughTimeFromLastChangePass(acc)) {
            	throw new ChangePasswordException();
            }
            if (context.enoughTimeFromLastUsage(acc)) {
            	acc.setRevoked(true);
            	return;
            }
            acc.setLoggedIn(true);
            if (!(context.getMapPass().containsKey(acc))) {
            	BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
                queue.put(password);
                context.getMapPass().putIfAbsent(acc, queue);
                context.getMapActivity().putIfAbsent(acc, new Date());
                context.getMapChangePass().putIfAbsent(acc, new Date());
            }
            context.setState(acc.getUserName(), new FirstFailedAttempt());
        } else {
            dealWithFailedAttempt(acc, context);
        }
    }

    protected abstract void dealWithFailedAttempt(IAccount acc, LoginService context);
    
}
